package com.developer.fans.upgrader;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.developer.fans.CrackApplication;
import com.developer.fans.MainActivity;
import com.developer.fans.R;

import java.io.File;

/**
 * Created by lu on 15-8-19.
 */
public class UpgraderView extends MainActivity.CrackItemView implements AppStoreUpgrader.AppStoreUpgraderListener {
    private AppStoreUpgrader.AppStoreUpgradeInfo info = null;
    private TextView text = null;
    private LinearLayout content = null;

    public UpgraderView() {
        super(CrackApplication.getContext().getResources().getString(R.string.update));
        AppStoreUpgrader.getInstance().setAppStoreUpgraderListener(this);
        content = new LinearLayout(CrackApplication.getContext());
        setContentView(content);
        text = new TextView(CrackApplication.getContext());
        content.addView(text);
    }

    @Override
    public void onClick(View v) {
        AppStoreUpgrader.getInstance().startCheck();
        text.setText("检测中，请稍后......");
    }

    @Override
    public void onUpgradeInfoReturn(AppStoreUpgrader.AppStoreUpgradeInfo info) {
        this.info = info;
        if (this.info != null)
            AppStoreUpgrader.getInstance().startUpgrade(this.info);
        else {
            post(new Runnable() {
                @Override
                public void run() {
                    text.setText("暂无更新");
                }
            });
        }
    }

    @Override
    public void onUpgradeDownloadStart() {
        post(new Runnable() {
            @Override
            public void run() {
                text.setText("开始下载");
            }
        });
    }

    @Override
    public void onUpgradeDownloadProcess(final int percent) {
        post(new Runnable() {
            @Override
            public void run() {
                text.setText("下载中:" + percent + "%");
            }
        });
    }

    @Override
    public void onUpgradeDownloadError() {
        post(new Runnable() {
            @Override
            public void run() {
                text.setText("下载失败");
            }
        });
    }

    @Override
    public void onUpgradeDownloadFinish(String apk_file) {
        if (info == null)
            return;
        post(new Runnable() {
            @Override
            public void run() {
                text.setText("下载完成");
            }
        });
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(apk_file)), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        CrackApplication.getContext().startActivity(intent);
    }
}
